/**
 * 用户主页JavaScript逻辑
 */

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    // 检查用户角色
    if (!Auth.checkRole(UserRole.NORMAL_USER)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    init();
});

function normalizeAppointmentList(data) {
    if (!data) {
        return [];
    }
    if (Array.isArray(data)) {
        return data;
    }
    if (Array.isArray(data.records)) {
        return data.records;
    }
    return [];
}

/**
 * 初始化页面
 */
async function init() {
    // 显示用户信息
    displayUserInfo();
    
    // 显示当前日期
    displayCurrentDate();
    
    // 加载统计数据
    await loadStatistics();
    
    // 加载最近预约
    await loadRecentAppointments();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = userInfo.account || '用户';
        document.getElementById('userName').textContent = userName;
        document.getElementById('welcomeName').textContent = userName;
        
        // 设置头像首字母
        const avatar = document.getElementById('userAvatar');
        avatar.textContent = userName.charAt(0).toUpperCase();
    }
}

/**
 * 显示当前日期
 */
function displayCurrentDate() {
    const now = new Date();
    const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
    const dateString = now.toLocaleDateString('zh-CN', options);
    document.getElementById('currentDate').textContent = dateString;
}

/**
 * 加载统计数据
 */
async function loadStatistics() {
    try {
        // 加载预约数量
        const appointmentPage = await HttpClient.get('/appointment/list');
        const appointments = normalizeAppointmentList(appointmentPage);
            document.getElementById('appointmentCount').textContent = appointments.length;
        
        // 加载家属数量
        const families = await HttpClient.get('/family/list');
        if (families && Array.isArray(families)) {
            document.getElementById('familyCount').textContent = families.length;
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

/**
 * 加载最近预约
 */
async function loadRecentAppointments() {
    try {
        const appointmentPage = await HttpClient.get('/appointment/list');
        const appointments = normalizeAppointmentList(appointmentPage);
        
        if (!appointments || appointments.length === 0) {
            return;
        }
        
        // 只显示最近5条
        const recentAppointments = appointments.slice(0, 5);
        
        const tbody = document.getElementById('recentAppointmentsBody');
        tbody.innerHTML = '';
        
        recentAppointments.forEach(appointment => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${appointment.personName || '-'}</td>
                <td>${appointment.vaccineName || '-'}</td>
                <td>${appointment.vaccinationSiteName || '-'}</td>
                <td>${Format.date(appointment.appointmentTime)}</td>
                <td>
                    <span class="badge ${Format.appointmentStatusBadge(appointment.appointmentStatus)}">
                        ${Format.appointmentStatus(appointment.appointmentStatus)}
                    </span>
                </td>
            `;
            tbody.appendChild(row);
        });
    } catch (error) {
        console.error('加载最近预约失败:', error);
        UI.showMessage('加载预约数据失败', 'danger');
    }
}

/**
 * 退出登录
 */
function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
        Auth.logout();
    }
}

